const FormData = require("form-data");
const axios = require("axios").default.create({
  headers: {
    "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.34 (KHTML, like Gecko) Chrome/62.0.3325.180 Safari/537.35 OPR/52.0.2871.41"
  }
});
const fs = require("fs");
const CommonAxerrHG = require("./CommonAxerrHandlerGenerator").CommonAxerrHandlerGen;
const Toolbox = require("./Toolbox");
const util = require("util");
const path = require("path");



const UPLOAD_URL = "https://www.wukong.com/wenda/web/upload/photo/?type=ueditor&editorid=write-ueditor-inline";


/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
 * @param {String} file_path 
 */
function uploadImage(file_path) {
  return new Promise(resolve => {
    let form = new FormData;
    let filestream = fs.createReadStream(file_path);

    form.append("upfile", filestream, {
      filename: `${Math.random()}.${path.basename(file_path)}.gif`,
      contentType:"image/gif"
    });
    // form.append("fileType", "idc_license");

    axios.post(UPLOAD_URL, form, {
      headers: {
        ...form.getHeaders(),
      },
      maxContentLength: Number.MAX_SAFE_INTEGER
    }).then(axresp => {
      // debugger
      if (axresp.data && axresp.data.url
        && util.isString(axresp.data.url)
        && axresp.data.url.includes("large")) {
        return resolve({
          data: {
            link: axresp.data.url.replace("/large/", "/origin/")
          },
          msg: "ok",
          ok: true
        })
      }
      throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
    }).catch(axerr => {
      CommonAxerrHG(resolve)(axerr);
    })
  })
}




module.exports = {
  uploadImage
}